package br.usp.ime.components.daos;

import java.util.List;

import org.hibernate.Session;
import org.hibernate.Transaction;
import org.hibernate.criterion.MatchMode;
import org.hibernate.criterion.Restrictions;

import br.com.caelum.vraptor.ioc.ApplicationScoped;
import br.com.caelum.vraptor.ioc.Component;
import br.usp.ime.entities.SubmittedFile;
import br.usp.ime.entities.Task;
import br.usp.ime.entities.Topic;
import br.usp.ime.entities.User;

@Component
@ApplicationScoped
public class SubmittedFileDao {
    
    private final Session session;
    
    public SubmittedFileDao(Session session) {
        this.session = session;
    }

	public void setSubmittedFile(SubmittedFile sf) {
		Transaction tx = this.session.beginTransaction();
        this.session.save(sf);
        tx.commit();		
	}
	
	@SuppressWarnings("unchecked")
    public List<SubmittedFile> loadFilesOf(Task task) {
    	List<SubmittedFile> list = (List<SubmittedFile>) this.session
                .createQuery("from SubmittedFile as s inner join fetch s.relatedTask as t where t.id = ?")
                .setLong(0,task.getId())
                .list();
    	return list;
    }	
	
	@SuppressWarnings("unchecked")
    public List<SubmittedFile> loadFilesOf(User user) {
		List<SubmittedFile> list = (List<SubmittedFile>) this.session
                .createQuery("from SubmittedFile as s inner join fetch s.submittedBy as t where t.login = ?")
                .setString(0, user.getLogin()).list();
    	return list;
    }	
	
    @SuppressWarnings("unchecked")
    public List<SubmittedFile> listAllSubmittedFiles() {
        return this.session.createCriteria(SubmittedFile.class).list();
    }
    
    public SubmittedFile loadFile(SubmittedFile sf) {
        if (sf == null)
            return null;
        session.clear();
        return (SubmittedFile) session.createCriteria(SubmittedFile.class)
                .add(Restrictions.eq("id", sf.getId())).uniqueResult();
    	
    }
    
    public void deleteSF(SubmittedFile sf) {
    	SubmittedFile sfTopic = loadFile(sf);
        if (sfTopic != null) {
            Transaction tx = this.session.beginTransaction();
            this.session.delete(sfTopic);
            tx.commit();
        }
    }
	

}
